//
//  MDTimer.m
//  Demo
//
//  Created by js on 15/9/11.
//  Copyright (c) 2015年 js. All rights reserved.
//

#import "LBCommonTimer.h"

#define kDaySecs (24 * 60 * 60) //天
#define kHourSecs (60 * 60)     //小时
#define kMinuteSecs 60          //分

@interface LBCommonTimer ()

@property (nonatomic, assign) NSTimer *timer;

@property (nonatomic, strong) NSMutableArray *timeUnits;
@end

@implementation LBCommonTimer

#pragma mark - Init

static LBCommonTimer *instance;
+ (instancetype)timer{
    @synchronized(self){
        if (!instance) {
            instance = [[LBCommonTimer alloc] init];
        }
    }
    return instance;
}

#pragma mark - Operation

- (void)addTimeUnit:(LBTimeUnit *)timeUnit{
    if (timeUnit == nil) {
        return;
    }
    [self.timeUnits addObject:timeUnit];
    
    if (![self.timer isValid]) {
        [self startTimer];
    }
}

- (void)removeTimeUnit:(LBTimeUnit *)timeUnit{
    if (timeUnit == nil) {
        return;
    }
    [_timeUnits removeObject:timeUnit];
    [self checkTimer];
}


- (void)deleteAllTimeUnits{
    [self stopTimer];
    [_timeUnits removeAllObjects];
}

- (void)checkTimer{
    if (self.timeUnits.count == 0) {
        [self stopTimer];
    }
}

- (void)startTimer{
    [self stopTimer];
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}


- (void)stopTimer{
    if ([self.timer isValid]) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)timerFired:(NSTimer *)timer{
    
    //更新所有timeUnit 的时间
    for (int i =0; i < self.timeUnits.count; i++){
        LBTimeUnit *timeUnit = self.timeUnits[i];
        if (timeUnit.timeInterval > 0) {
            timeUnit.timeInterval --;
            
            if (timeUnit.plainUpdateBlock) {
                timeUnit.plainUpdateBlock(timeUnit.timeInterval);
            }
            
            if (timeUnit.updateBlock) {
                [[self class] parseTime:timeUnit.timeInterval complete:timeUnit.updateBlock];
            }
        }
        else{
            if (timeUnit.completeBlock) {
                timeUnit.completeBlock();
            }
            
            [self.timeUnits removeObject:timeUnit];
            i--;
            
            [self checkTimer];
            
        }
    }
}

+ (void)parseTime:(NSUInteger)time complete:(LBTimerUpdateBlock)block{
 
    NSUInteger day = time / kDaySecs;
    time = time % kDaySecs;
    
    NSUInteger hour = time / kHourSecs;
    time = time % kHourSecs;
    
    NSUInteger minute = time / kMinuteSecs;
    
    NSUInteger sec = time % kMinuteSecs;
    if (block) {
        block(day,hour,minute,sec);
    }
}

#pragma mark - Property

- (NSMutableArray *)timeUnits{
    if (!_timeUnits) {
        _timeUnits = [[NSMutableArray alloc] init];
    }
    return _timeUnits;
}
@end
